<!-- templates/datasource_form.html -->
{% extends 'base.html' %}

{% block title %}创建数据源{% endblock %}

{% block content %}
<!-- 主页面内容 -->
<div class="container mt-4">
    <div class="row justify-content-start">
    <div class="col-12 col-md-8 col-lg-10"> <!-- 右侧70%宽度 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3">数据源管理</h1>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createDataSourceModal">
            <i class="fa fa-plus"></i> 新建数据源
        </button>
    </div>
    <!-- 搜索框 -->
    <div class="mb-3 d-flex">
        <input type="text" id="datasourceSearchInput" class="form-control me-2" placeholder="搜索数据源名称/描述...">
        <button id="datasourceSearchBtn" class="btn btn-outline-secondary" type="button">
            <i class="fa fa-search"></i> 
        </button>
    </div>
    
    {% if messages %}
        {% for message in messages %}
            <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
                {{ message }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        {% endfor %}
    {% endif %}
    
    <!-- 数据源列表表格 -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th class="px-3 text-center" style="width: 15%;">名称</th>
                            <th class="px-3 text-center" style="width: 15%;">表格数量</th>
                            <th class="px-3 text-center" style="width: 25%;">描述</th>
                            <th class="px-3 text-center" style="width: 20%;">创建时间</th>
                            <th class="px-3 text-center" style="width: 25%;">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for datasource in data_sources %}
                        <tr>
                            <td class="px-3 text-center">{{ datasource.name }}</td>
                            <td class="px-3 text-center">{{ datasource.tables.count }}</td>
                            <td class="px-3 text-center">{{ datasource.description|truncatechars:50 }}</td>
                            <td class="px-3 text-center">{{ datasource.created_at|date:"Y-m-d H:i" }}</td>
                            <td class="px-3">
                                <!-- <a href="{% url 'table_list' datasource_pk=datasource.pk %}" class="btn btn-sm btn-outline-secondary">
                                    <i class="fa fa-list"></i> 查看表格
                                </a> -->
                                <button type="button"
                                    class="btn btn-sm btn-outline-secondary config-tables-btn"
                                    data-id="{{ datasource.pk }}"
                                    data-name="{{ datasource.name }}">
                                    <i class="fa fa-list"></i> 配置
                                </button>
                                <!-- <a href="#" 
                                    class="btn btn-sm btn-outline-primary edit-datasource-btn"
                                    data-bs-toggle="modal"
                                    data-bs-target="#editDataSourceModal"
                                    data-id="{{ datasource.pk }}"
                                    data-name="{{ datasource.name }}"
                                    data-description="{{ datasource.description }}">
                                        <i class="fa fa-edit"></i> 详情
                                </a> -->
                                <button type="button"
                                   class="btn btn-sm btn-outline-primary edit-datasource-btn"
                                   data-bs-toggle="modal"
                                   data-bs-target="#editDataSourceModal"
                                   data-id="{{ datasource.pk }}"
                                   data-name="{{ datasource.name }}"
                                   data-description="{{ datasource.description }}"
                                   data-engine="{{ datasource.engine }}"
                                   data-user="{{ datasource.user }}"
                                   data-password="{{ datasource.password }}"
                                   data-host="{{ datasource.host }}"
                                   data-port="{{ datasource.port }}">
                                    <i class="fa fa-edit"></i> 编辑
                                </button>
                                <form method="post" action="{% url 'datasource_delete' pk=datasource.pk %}" style="display:inline;">
                                    {% csrf_token %}
                                    <button type="submit" class="btn btn-sm btn-outline-danger" onclick="return confirm('确定要删除吗？');">
                                        <i class="fa fa-trash"></i> 删除
                                    </button>
                                </form>
                            </td>
                        </tr>
                        {% empty %}
                        <tr>
                            <td colspan="5" class="text-center text-muted py-4">
                                <i class="fa fa-folder-open-o fa-3x mb-2"></i>
                                <p>暂无数据源，请创建一个新的数据源。</p>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    </div>
    </div>
</div>

<!-- 创建数据源模态框 -->
<div class="modal fade" id="createDataSourceModal" tabindex="-1" aria-labelledby="createDataSourceModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form method="post" id="createDataSourceForm">
                <!-- CSRF令牌应放在表单开始位置 -->
                {% csrf_token %}
                <input type="hidden" id="create_id_pk" name="pk" value={{datasource_pk}}>
                <div class="modal-header">
                    <h5 class="modal-title" id="createDataSourceModalLabel">创建数据源</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <!-- 数据源名称 -->
                    <div class="mb-3">
                        <label for="id_name" class="form-label">名称<span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="id_name" name="name" required>
                    </div>
                    <!-- 引擎 -->
                    <div class="mb-3">
                        <label for="id_engine" class="form-label">引擎<span class="text-danger">*</span></label>
                        <select class="form-select" id="id_engine" name="engine" required>
                            <option value="">请选择</option>
                            <option value="mysql">MySQL</option>
                            <option value="postgresql">PostgreSQL</option>
                            <option value="sqlite">SQLite</option>
                            <option value="oracle">Oracle</option>
                        </select>
                    </div>
                    <!-- 用户名 -->
                    <div class="mb-3">
                        <label for="id_user" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="id_user" name="user">
                    </div>
                    <!-- 密码 -->
                    <div class="mb-3">
                        <label for="id_password" class="form-label">密码</label>
                        <input type="password" class="form-control" id="id_password" name="password">
                    </div>
                    <!-- 主机 -->
                    <div class="mb-3">
                        <label for="id_host" class="form-label">主机</label>
                        <input type="text" class="form-control" id="id_host" name="host">
                    </div>
                    <!-- 端口 -->
                    <div class="mb-3">
                        <label for="id_port" class="form-label">端口</label>
                        <input type="number" class="form-control" id="id_port" name="port">
                    </div>
                    <!-- 描述 -->
                    <div class="mb-3">
                        <label for="id_description" class="form-label">描述</label>
                        <textarea class="form-control" id="id_description" name="description" rows="3"></textarea>
                    </div>
                </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
            <i class="fa fa-times mr-1"></i>取消
        </button>
        <button type="submit" class="btn btn-primary">
            <i class="fa fa-check mr-1"></i>保存
        </button>
    </div>
</form>
</div>
    </div>
</div>

<!-- 编辑数据源模态框 -->
<div class="modal fade" id="editDataSourceModal" tabindex="-1" aria-labelledby="editDataSourceModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form method="post" id="editDataSourceForm">
                {% csrf_token %}
                <div class="modal-header">
                    <h5 class="modal-title" id="editDataSourceModalLabel">编辑数据源</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <input type="hidden" id="edit_id_pk" name="pk" value="{{ datasource.pk }}">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="edit_id_name" class="form-label">名称<span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="edit_id_name" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label for="edit_id_engine" class="form-label">引擎<span class="text-danger">*</span></label>
                        <select class="form-select" id="edit_id_engine" name="engine" required>
                            <option value="">请选择</option>
                            <option value="mysql">MySQL</option>
                            <option value="postgresql">PostgreSQL</option>
                            <option value="sqlite">SQLite</option>
                            <option value="oracle">Oracle</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="edit_id_user" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="edit_id_user" name="user">
                    </div>
                    <div class="mb-3">
                        <label for="edit_id_password" class="form-label">密码</label>
                        <input type="password" class="form-control" id="edit_id_password" name="password">
                    </div>
                    <div class="mb-3">
                        <label for="edit_id_host" class="form-label">主机</label>
                        <input type="text" class="form-control" id="edit_id_host" name="host">
                    </div>
                    <div class="mb-3">
                        <label for="edit_id_port" class="form-label">端口</label>
                        <input type="number" class="form-control" id="edit_id_port" name="port">
                    </div>
                    <div class="mb-3">
                        <label for="edit_id_description" class="form-label">描述</label>
                        <textarea class="form-control" id="edit_id_description" name="description" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fa fa-times mr-1"></i>取消
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-check mr-1"></i>保存
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 表格名复选框 -->
<div class="modal fade" id="configTablesModal" tabindex="-1" aria-labelledby="configTablesModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <form id="configTablesForm">
        {% csrf_token %}
        <div class="modal-header">
          <h5 class="modal-title" id="configTablesModalLabel">选择表格</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
            <div class="mb-2">
              <input type="text" class="form-control" id="tableSearchInput" placeholder="搜索表名...">
            </div>
            <div id="tablesCheckboxList">
                <!-- 这里用JS动态填充表名复选框 -->
            </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
          <button type="submit" class="btn btn-primary">保存选择</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="configFieldsModal" tabindex="-1" aria-labelledby="configFieldsModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <form id="configFieldsForm">
        {% csrf_token %}
        <div class="modal-header">
          <h5 class="modal-title" id="configFieldsModalLabel">选择字段</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
            <div class="mb-2">
                <input type="text" class="form-control" id="fieldSearchInput" placeholder="搜索字段名...">
            </div>
            <div id="fieldsCheckboxList">
                <!-- JS动态填充字段复选框 -->
            </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
          <button type="submit" class="btn btn-primary">保存选择</button>
        </div>
      </form>
    </div>
  </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        //监听所有编辑按钮
        document.querySelectorAll('.edit-datasource-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                document.getElementById('edit_id_pk').value = btn.getAttribute('data-id') || '';
                document.getElementById('edit_id_name').value = btn.getAttribute('data-name') || '';
                document.getElementById('edit_id_description').value = btn.getAttribute('data-description') || '';
                document.getElementById('edit_id_engine').value = btn.getAttribute('data-engine') || '';
                document.getElementById('edit_id_user').value = btn.getAttribute('data-user') || '';
                document.getElementById('edit_id_password').value = btn.getAttribute('data-password') || '';
                document.getElementById('edit_id_host').value = btn.getAttribute('data-host') || '';
                document.getElementById('edit_id_port').value = btn.getAttribute('data-port') || '';
            });
        });
        // 配置按钮监听（修正后）
        let currentDatasourceId = null;
        
        document.querySelectorAll('.config-tables-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                currentDatasourceId = btn.getAttribute('data-id'); // 记录当前数据源id
                fetch(`/api/datasource/${currentDatasourceId}/tables/`)
                    .then(response => response.json())
                    .then(data => {
                        const tablesDiv = document.getElementById('tablesCheckboxList');
                        tablesDiv.innerHTML = '';
                        data.tables.forEach(function(table) {
                            tablesDiv.innerHTML += `
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" value="${table.id}" id="table_${table.id}" ${table.is_show ? 'checked' : ''}>
                                    <a href="javascript:void(0);" class="table-name-link" data-table-id="${table.id}" data-table-name="${table.name}">
                                        ${table.name}
                                    </a>
                                </div>
                            `;
                        });
                        var modal = new bootstrap.Modal(document.getElementById('configTablesModal'));
                        modal.show();
                    });
            });
        });
        
        document.getElementById('configTablesForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const checkedIds = Array.from(document.querySelectorAll('#tablesCheckboxList input[type="checkbox"]:checked')).map(cb => cb.value);
            // 用当前点击的 data-id
            fetch(`/api/datasource/${currentDatasourceId}/tables/set_show/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                },
                body: JSON.stringify({show_ids: checkedIds})
            }).then(res => res.json()).then(data => {
                location.reload();
            });
        });

        // 监听表名搜索框，实现弹窗内表名过滤
        document.getElementById('tableSearchInput').addEventListener('input', function() {
            const keyword = this.value.trim().toLowerCase();
            document.querySelectorAll('#tablesCheckboxList .form-check').forEach(function(div) {
                const label = div.querySelector('label').innerText.toLowerCase();
                div.style.display = label.includes(keyword) ? '' : 'none';
            });
        });
        // 监听表名链接点击事件，获取字段数据
        let currentTableId = null;
        
        document.getElementById('tablesCheckboxList').addEventListener('click', function(e) {
            if (e.target.classList.contains('table-name-link')) {
                const tableId = e.target.getAttribute('data-table-id');
                const checkbox = document.getElementById('table_' + tableId);
                if (!checkbox.checked) {
                    alert('请先勾选该表格，再选择字段！');
                    return;
                }
                currentTableId = tableId; // 记录当前表id
                fetch(`/api/table/${tableId}/fields/`)
                    .then(response => response.json())
                    .then(data => {
                        const fieldsDiv = document.getElementById('fieldsCheckboxList');
                        fieldsDiv.innerHTML = '';
                        data.fields.forEach(function(field) {
                            fieldsDiv.innerHTML += `
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" value="${field.id}" id="field_${field.id}" ${field.is_show ? 'checked' : ''}>
                                    <label class="form-check-label" for="field_${field.id}">
                                        ${field.name}
                                    </label>
                                </div>
                            `;
                        });
                        var modal = new bootstrap.Modal(document.getElementById('configFieldsModal'));
                        modal.show();
                    });
            }
        });
        // 字段弹窗内字段名搜索
        document.getElementById('fieldSearchInput').addEventListener('input', function() {
            const keyword = this.value.trim().toLowerCase();
            document.querySelectorAll('#fieldsCheckboxList .form-check').forEach(function(div) {
                const label = div.querySelector('label').innerText.toLowerCase();
                div.style.display = label.includes(keyword) ? '' : 'none';
            });
        });
                document.getElementById('configFieldsForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const checkedFieldIds = Array.from(document.querySelectorAll('#fieldsCheckboxList input[type="checkbox"]:checked')).map(cb => cb.value);
            if (!currentTableId) return;
            fetch(`/api/table/${currentTableId}/fields/set_show/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                },
                body: JSON.stringify({show_ids: checkedFieldIds})
            }).then(res => res.json()).then(data => {
                var fieldsModal = bootstrap.Modal.getInstance(document.getElementById('configFieldsModal'));
                fieldsModal.hide();
                var tablesModal = new bootstrap.Modal(document.getElementById('configTablesModal'));
                tablesModal.show();
            });
        });
        // 搜索功能
        function filterTable() {
            const keyword = document.getElementById('datasourceSearchInput').value.trim().toLowerCase();
            document.querySelectorAll('table tbody tr').forEach(function(row) {
                const text = row.innerText.toLowerCase();
                row.style.display = text.includes(keyword) ? '' : 'none';
            });
        }
        const searchInput = document.getElementById('datasourceSearchInput');
        const searchBtn = document.getElementById('datasourceSearchBtn');
        if (searchInput && searchBtn) {
            searchBtn.addEventListener('click', filterTable);
            searchInput.addEventListener('keydown', function(e) {
                if (e.key === 'Enter') filterTable();
            });
        }
        });
</script>
{% endblock %}